package org.btik.lightweb.util;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.light.tool.type.StringUtil;

import static org.btik.light.tool.type.StringUtil.safeValue;

/**
 * @author lustre
 * @since 2023/6/12 15:39
 */
public class WebUtil {
    private static final Log LOG = LogFactory.getLog(WebUtil.class);

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
            }
            // 通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null) {
                if (ipAddress.contains(",")) {
                    return ipAddress.split(",")[0];
                } else {
                    return ipAddress;
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            LOG.error("", e);
            return "";
        }
    }

    public static String getRequestFrom(HttpServletRequest request) {
        return request.getHeader("User-Agent") + '\n' + safeValue(request.getHeader("x-forwarded-for")) + '/'
                + safeValue(request.getHeader("Proxy-Client-IP")) + '/'
                + safeValue(request.getHeader("WL-Proxy-Client-IP")) + '/'
                + safeValue(request.getRemoteAddr())
                ;
    }
}
